﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Sever2
{
    class Conn
    {
        //缓存区大小
        public const int BUFFER_SIZE = 1024;
        //socket
        public Socket socket;
        //是否被使用
        public bool isUse = false;
        //Buff
        public byte[] readBuff;
        public int buffCount = 0;

        public DateTime time { get; private set; }

        //构造函数
        public Conn()
        {
            readBuff = new byte[BUFFER_SIZE];
        }

        public void refresh()
        {
            time = DateTime.Now;
        }
        //初始化
        public void Init(Socket socket)
        {
            this.socket = socket;
            isUse = true;
            buffCount = 0;
            time = DateTime.Now;
        }
        private byte[] KeepAlive(int onOff, int keepAliveTime, int keepAliveInterval)
        {
            byte[] buffer = new byte[12];
            BitConverter.GetBytes(onOff).CopyTo(buffer, 0);
            BitConverter.GetBytes(keepAliveTime).CopyTo(buffer, 4);
            BitConverter.GetBytes(keepAliveInterval).CopyTo(buffer, 8);
            return buffer;
        }
        //缓存区剩余的字节
        public int BuffRemain()
        {
            return BUFFER_SIZE - buffCount;
        }

        //获取客户端的地址
        public string GetAddress()
        {
            if (!isUse)
                return "获取地址失败";

            return socket.RemoteEndPoint.ToString();
        }

        //关闭
        public void Close()
        {
            if (!isUse)
                return;

            Console.WriteLine(GetAddress() + " 断开连接");
            socket.Close();
            isUse = false;
        }
    }
}
